package top.zhangjianyong.tools.service.api.impl;

import be.adaxisoft.bencode.BDecoder;
import be.adaxisoft.bencode.BEncodedValue;
import be.adaxisoft.bencode.BEncoder;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.zhangjianyong.tools.entity.Torrent;
import top.zhangjianyong.tools.factory.TorrentFactory;
import top.zhangjianyong.tools.service.api.TorrentService;
import top.zhangjianyong.tools.service.mybatis.ITorrentService;
import top.zhangjianyong.tools.utils.ApiResponse;
import top.zhangjianyong.tools.utils.DateTimeUtil;
import top.zhangjianyong.tools.utils.FileUtil;
import top.zhangjianyong.tools.utils.UUIDUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.time.Year;
import java.time.YearMonth;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author ： zhangjianyong
 * @date ： 2023/3/22 2:22 PM
 */
@Service
public class TorrentServiceImpl implements TorrentService {

    private final static String MAGNET_HEADER = "magnet:?xt=urn:btih:";

    @Value("${torrent.file.path}")
    private String filePath;
    @Autowired
    private ITorrentService iTorrentService;

    @Override
    public ApiResponse torrentToMagnet(MultipartFile torrentFile) throws IOException, NoSuchAlgorithmException {
        if (!torrentFile.getOriginalFilename().toLowerCase().endsWith(".torrent")) {
            return ApiResponse.fail("种子文件格式不正确");
        }
        String md5 = FileUtil.md5(torrentFile.getInputStream());
        Torrent one = iTorrentService.qryByMd5(md5);
        String fileName = UUIDUtil.randomFileName("torrent");
        if (one != null) {
            fileName = one.getFileName();
        }


        String yearMonth = DateTimeUtil.yearMonth();
        String path = filePath + File.separator + yearMonth;
        Map<String, BEncodedValue> infoMap = BDecoder.decode(torrentFile.getInputStream())
                .getMap()
                .get("info")
                .getMap();
        String hash = DigestUtils.sha1Hex(BEncoder.encode(infoMap).array()).toUpperCase();
        String magnet = MAGNET_HEADER + hash;
        File saveFile = FileUtil.saveFile(torrentFile, path, fileName);


        Torrent torrent = TorrentFactory
                .create(magnet, hash, torrentFile.getOriginalFilename(), saveFile.getPath(), md5, fileName);

        if (null == one) {
            iTorrentService.save(torrent);
        } else {
            torrent.setId(one.getId());
            iTorrentService.updateById(torrent);
        }

        return ApiResponse.success(torrent);
    }

    @Override
    public ApiResponse list() {
        List<Torrent> torrents = iTorrentService.listOrderByUpdate();
        return ApiResponse.success(torrents);
    }

    public static void main(String[] args) throws IOException {
        File file = new File("/Users/zhangjianyong/Downloads/Infernal.Affairs.II.2003.BluRay.1080p.x265.10bit.2Audio-MiniHD[BTBTT].torrent");
        BEncodedValue decode = BDecoder.decode(new FileInputStream(file));
        Map<String, BEncodedValue> map = decode.getMap();
        BEncodedValue info = map.get("info");
        Map<String, BEncodedValue> infoMap = info.getMap();
        String hash = DigestUtils.sha1Hex(BEncoder.encode(infoMap).array()).toUpperCase();
        map.get("created by").getString();
        System.out.println(hash);
    }
}
